<template>
  <div>
    <div @click="btnClick">
      <a-tooltip :title="treeKey.value ? '' : '请选择公司'" v-if="!isSlot">
        <a-button type="primary" :loading="btnLoading" :ghost="true" :disabled="!treeKey.value">
          隐患排查台账导出
        </a-button>
      </a-tooltip>
      <slot v-else></slot>
    </div>
    <a-modal v-model="visible" title="隐患排查台账导出" @ok="handleOk">
      <a-form :form="form" :model="formData" :layout="formLayout">
        <a-form-item label="隐患排查" name="name">
          <a-select show-search :options="selectList"
            v-decorator="['name', { rules: [{ required: true, message: '请选择隐患排查' }] }]">
          </a-select>
        </a-form-item>
        <!-- @change="handleDateChange" -->
        <a-form-item label="日期" name="day">
          <a-range-picker v-decorator="[
            'day',
            { rules: [{ required: true, message: '请选择日期' }, { validator: validateDate }] },
          ]" style="width: 100%" :disabled-date="disabledDate" format="YYYY-MM-DD">
          </a-range-picker>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import moment from "moment";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
export default {
  name: "ZSUpload",
  props: {
    name: {
      type: String,
      default: "青岛港董矿公司隐患排查治理流程",
    },
    isSlot: {
      type: Boolean,
      default: false,
    },
    treeKey: {
      type: Object,
      default: () => { }
    },
    sponsoredUnit: {
      type: [Number, String],
    }
  },
  data() {
    return {
      visible: false,
      btnLoading: false,
      selectList: [],
      formData: {
        name: "",
        day: "",
      },
      formLayout: "horizontal",
      form: this.$form.createForm(this, { name: "coordinated" }),
      loading: false,
      timestamp: "",
      timeOut: null,
      sendParams: {},
      maxData: 32,
    };
  },
  methods: {
    validateDate(rule, value, callback) {
      if (!value) {
        callback("请输入日期");
      } else if (value.length > 0) {
        let startTime = moment(value[0]);
        let endTime = moment(value[1]);
        let diffDays = endTime.diff(startTime, "days");
        if (diffDays >= this.maxData) {
          callback(`日期区间不能大于${this.maxData}天`);
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    handleDateChange(dates, dateStrings) {
      if (dates && dates.length === 2) {
        const daysDiff = this.getDaysBetween(dates[0], dates[1]);
        if (daysDiff > 45) {
          this.$message.error("日期范围最多只能选择45天");
          // 重置为原来的日期范围或设置为允许的日期范围
          this.dateRange = [...this.originalDateRange];
        } else {
          // 更新原始日期范围
          this.originalDateRange = [...dates];
        }
      }
    },
    getDaysBetween(date1, date2) {
      const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
      const firstDate = new Date(date1);
      const secondDate = new Date(date2);

      return Math.round(Math.abs((firstDate - secondDate) / oneDay));
    },
    btnClick() {
      this.getSelectData();
    },
    handleOk() {
      this.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          let formData = values;
          if (Array.isArray(formData["day"])) {
            formData["day"] = formData["day"].map((val) => moment(val).format("YYYY-MM-DD"));
          } else if (typeof formData["day"] == "string") {
            formData["day"] = moment(formData["day"]).format("YYYY-MM-DD");
          }
          let params = {
            sMonth: formData.day[0],
            eMonth: formData.day[1],
            name: formData.name,
          };
          this.getUpload(params);
        }
      });
    },
    // 下载文件
    getUpload(aParams) {
      let nowTimes = new Date().getTime();
      this.timestamp = nowTimes;
      let params = {
        name: aParams.name,
        sMonth: aParams.sMonth,
        eMonth: aParams.eMonth,
        id: nowTimes,
      };
      this.sendParams = params;
      // 请求 url 让后端开始导出
      {
        this.getAxios(this.$doGet, params, {}, { responseType: "blob" })
          .then((res) => {
            if (res) {
              this.loading = true;
              const blob = new Blob([res], {
                type: "vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
              }); // 构造一个blob对象来处理数据，并设置文件类型
              const link = document.createElement("a");
              link.style.display = "none";
              // 兼容不同浏览器的URL对象
              const url = window.URL || window.webkitURL || window.moxURL;
              link.href = url.createObjectURL(blob);
              link.setAttribute("download", `${params.name}${params.sMonth}-${params.eMonth}.xlsx`);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              url.revokeObjectURL(link.href);
            }
          })
          .finally(() => {
            this.$notification.close(this.timestamp);
            this.loading = false;
          });
      }
      this.start();
      this.visible = false;
      this.$notification.open({
        key: nowTimes,
        duration: null,
        message: "提示",
        description: "制单中，请稍后",
        onClick: () => { },
        icon: <a-icon type="question-circle" />,
      });
      setTimeout(() => {
        this.form.resetFields();
      }, 1000);
    },
    getSelectData() {
      this.btnLoading = true;
      let params = {
        companyId: this.treeKey.value,
      };
      this.getAxios(this.$gethiddentype, params)
        .then((res) => {
          if (res.code == 200) {
            this.selectList = res.data.map((val) => {
              return {
                value: val.name,
                label: val.name,
              };
            });
            this.sendParams = {};
            this.visible = true;
          }
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },
    disabledDate(current) {
      return current && moment(current).format("YYYY-MM-DD") > moment().format("YYYY-MM-DD");
    },
    start() {
      this.loading = true;
      this.timeOut = setTimeout(() => {
        this.getPress();
      }, 2000);
    },
    getPress() {
      let params = {
        id: this.timestamp,
      };
      this.getAxios(this.$getschedule, params)
        .then((res) => {
          if (res.code == 200) {
            let data = res.data;
            if (data == 1) {
              this.loading = false;
              this.$notification.close(this.timestamp);
              this.$notification.open({
                key: this.timestamp,
                duration: null,
                message: "提示",
                icon: <a-icon type="check-circle" style="color:green" />,
                description: (
                  <div>
                    <span>制单成功！等待下载</span>
                    <br />
                    <span>(导出天数过大会导致等待时间过长)</span>
                  </div>
                ),
                onClick: () => { },
              });
            } else {
              this.start();
              this.$notification.open({
                key: this.timestamp,
                duration: null,
                message: "提示",
                description: `制单中，请稍后(当前进度${(Number(data) * 100).toFixed(0)}%)`,
                icon: <a-icon type="loading" style="color: #108ee9" />,
                onClick: () => { },
              });
            }
          }
        })
        .finally(() => { });
    },
    end(tName) {
      if (tName) {
        clearTimeout(tName);
      } else {
        clearTimeout(this.timeOut);
      }
    },
  },
  destroyed() {
    this.end();
  },
  watch:{
    visible:{
      handler(nVal,oVal){
        if(!nVal){
          this.form.resetFields();
        }
      },
      deep:true,
      immediate:true,
    }
  }
};
</script>
<style lang="less" scoped></style>
